<template>
  <div class="app-container">
    <!-- 内容区域 - 知识库 -->
    <div class="content-container dataset-container">
      <div class="welcome-header">
        <div class="welcome-text">
          <!-- <h2>欢迎回来，{{ userName }}</h2> -->
          <!-- <p>今天我们使用哪个知识库？</p> -->
        </div>
        <div class="action-buttons">
          <el-input 
            v-model="queryParams.keyword" 
            placeholder="搜索知识库" 
            clearable
            @keyup.enter="handleQuery"
            class="search-input" 
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" icon="Plus" @click="handleCreate">创建知识库</el-button>
        </div>
      </div>
      
      <div class="dataset-content-wrapper">
        <div v-loading="loading" class="dataset-cards">
          <el-empty v-if="datasetList.length === 0" description="暂无知识库数据" />
          <el-row v-else :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" v-for="(item, index) in datasetList" :key="index">
              <el-card class="dataset-card" shadow="hover" @click="handleViewDataset(item)">
                <div class="dataset-card-header">
                  <el-avatar :size="36" :src="item.dataset_avatar || ''" :icon="!item.dataset_avatar ? User : ''" />
                  <div class="dataset-card-actions" @click.stop>
                    <el-dropdown trigger="hover" @command="handleCommand($event, item)">
                      <span class="el-dropdown-link">
                        <el-icon color="#999"><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <!-- <el-dropdown-item command="edit">编辑</el-dropdown-item> -->
                          <!-- <el-dropdown-item command="upload">上传文档</el-dropdown-item> -->
                          <el-dropdown-item command="delete" icon="delete" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
                <div class="dataset-card-body">
                  <div class="dataset-num">{{ item.id }}</div>
                  <div class="dataset-name">{{ item.dataset_name }}</div>
                </div>
                <div class="dataset-card-footer">
                  <div class="dataset-info">
                    <el-icon><Document /></el-icon>
                    <span>{{ item.dataset_document_count || 0 }} 文档</span>
                  </div>
                  <div class="dataset-date">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDate(item.createTime) }}</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <div class="pagination-footer">
        <div v-if="datasetList.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[8, 12, 24, 36]"
            :layout="'total, sizes, prev, pager, next, jumper'"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 创建/编辑知识库对话框 -->
    <el-dialog 
      :title="dialogType === 'create' ? '创建知识库' : '编辑知识库'" 
      v-model="dialogVisible" 
      width="500px"
      append-to-body
    >
      <el-form ref="datasetFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="知识库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <!-- <el-form-item label="知识库描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入知识库描述" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 上传文档对话框 -->
    <el-dialog 
      title="上传文档" 
      v-model="uploadVisible" 
      width="500px"
      append-to-body
    >
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .pdf, .doc, .docx, .txt, .md 格式文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { Document, Calendar, MoreFilled, Search, Plus, User, UploadFilled } from '@element-plus/icons-vue'
import { listData, addData, updateData, deleteData } from '@/api/knowledge/dataset'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

// 用户名 - 从用户信息中获取
const userName = ref('betty')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
  keyword: ''
})

// 数据相关
const loading = ref(false)
const datasetList = ref([])
const total = ref(0)
const isLastPage = computed(() => {
  return total.value <= queryParams.pageNum * queryParams.pageSize
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const submitLoading = ref(false)
const form = reactive({
  id: undefined,
  name: '',
  description: ''
})
const rules = {
  name: [
    { required: true, message: '知识库名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
}
const datasetFormRef = ref(null)

// 上传相关
const uploadVisible = ref(false)
const currentDatasetId = ref(null)
const uploadUrl = computed(() => {
  return `/api/knowledge/dataset/${currentDatasetId.value}/upload`
})
const uploadHeaders = computed(() => {
  return { Authorization: 'Bearer ' + getToken() }
})

// 格式化日期
function formatDate(timestamp) {
  return parseTime(timestamp, '{y}-{m}-{d} {h}:{i}')
}

// 获取知识库列表
function getList() {
  loading.value = true
  listData(queryParams).then(response => {
    datasetList.value = response.data.rows || []
    total.value = response.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 处理查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 处理页面大小变化
function handleSizeChange(size) {
  queryParams.pageSize = size
  getList()
}

// 处理当前页变化
function handleCurrentChange(page) {
  queryParams.pageNum = page
  getList()
}

// 处理创建知识库
function handleCreate() {
  dialogType.value = 'create'
  form.id = undefined
  form.name = ''
  form.description = ''
  dialogVisible.value = true
  // 等待DOM更新后设置焦点
  setTimeout(() => {
    datasetFormRef.value?.resetFields()
  }, 0)
}

// 处理编辑知识库
function handleEdit(row) {
  dialogType.value = 'edit'
  form.id = row.id
  form.name = row.name
  form.description = row.description
  dialogVisible.value = true
  // 等待DOM更新后设置焦点
  setTimeout(() => {
    datasetFormRef.value?.resetFields()
  }, 0)
}

// 处理删除知识库
function handleDelete(row) {
  proxy.$modal.confirm(`确定要删除知识库"${row.dataset_name}"吗？删除后不可恢复。`).then(() => {
    deleteData(row.datasetId).then(() => {
      proxy.$modal.msgSuccess("删除成功")
      getList()
    }).catch(() => {})
  }).catch(() => {})
}

// 处理下拉菜单命令
function handleCommand(command, row) {
  switch (command) {
    case 'edit':
      handleEdit(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'upload':
      currentDatasetId.value = row.id
      uploadVisible.value = true
      break
    default:
      break
  }
}

// 处理查看知识库详情
function handleViewDataset(row) {
  console.log(row,'row')
  // 把row.dataset_uuid 存下来  test 页面要用
  localStorage.setItem('ids', JSON.stringify({dataset_uuid:row.dataset_uuid,dataset_id:row.datasetId,dataset_name:row.dataset_name}))
  // 跳转到知识库详情页面
  proxy.$router.push(`/knowledge/dataset/${row.datasetId}`);
}

// 提交表单
function submitForm() {
  datasetFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const submitData = { ...form }
      
      if (dialogType.value === 'create') {
        addData(submitData).then(response => {
          proxy.$modal.msgSuccess("创建成功")
          localStorage.setItem('dataset_id', JSON.stringify(response.data.datasetId))
          dialogVisible.value = false
          // getList()
          // 跳转到配置页面
          const id = JSON.parse(localStorage.getItem('dataset_id'))
          if(id){
            proxy.$router.push(`/knowledge/setting`)
          }
        }).catch(() => {}).finally(() => {
          submitLoading.value = false
        })
      } else {
        updateData(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          dialogVisible.value = false
          getList()
        }).catch(() => {}).finally(() => {
          submitLoading.value = false
        })
      }
    }
  })
}

// 上传文件前的验证
function beforeUpload(file) {
  // 检查文件类型
  const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'text/markdown']
  const validExtensions = ['.pdf', '.doc', '.docx', '.txt', '.md']
  
  const isValidType = validTypes.includes(file.type)
  const extension = '.' + file.name.split('.').pop().toLowerCase()
  const isValidExtension = validExtensions.includes(extension)
  
  if (!isValidType && !isValidExtension) {
    proxy.$modal.msgError('仅支持 PDF、Word、TXT 和 Markdown 类型的文件!')
    return false
  }
  
  // 检查文件大小
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    proxy.$modal.msgError('文件大小不能超过 20MB!')
    return false
  }
  
  return true
}

// 上传成功处理
function handleUploadSuccess(response, file, fileList) {
  proxy.$modal.msgSuccess("文件上传成功")
  
  // 上传完毕后刷新知识库列表
  if (fileList.length === fileList.filter(f => f.status === 'success').length) {
    getList()
    uploadVisible.value = false
  }
}

// 上传错误处理
function handleUploadError(error, file, fileList) {
  proxy.$modal.msgError("文件上传失败")
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.content-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;
}

.welcome-text h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #303133;
}

.welcome-text p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

/* 卡片相关样式 */
.dataset-cards {
  margin-bottom: 0;
}

.el-row {
  row-gap: 24px;
  margin-bottom: 0 !important;
}

.el-col {
  padding-bottom: 0;
  margin-bottom: 0;
}

.dataset-card {
  height: 100%;
  border-radius: 8px;
  transition: all 0.2s;
  cursor: pointer;
  padding: 20px;
  display: flex;
  flex-direction: column;
  margin: 0;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, .3);
}

.dataset-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dataset-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dataset-card-actions {
  cursor: pointer;
}

.dataset-card-body {
  flex: 1;
  padding: 15px 0;
  text-align: center;
  /* display: flex; */
  flex-direction: row;
  justify-content: center;
  min-height: 80px;
}

.dataset-num {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.dataset-name {
  font-size: 24px;
  color: #000000e0;
  margin-bottom: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
  font-weight: bold;
}

.dataset-card-footer {
  display: inline;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #000000e0;
  margin-top: 20px;
  padding-top: 15px;
  font-weight: bold;
  /* border-top: 1px solid #f0f0f0; */
}

.dataset-info, .dataset-date {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  
}

/* 分页相关样式 */
.pagination-footer {
  margin-top: 10px;
  padding: 15px 0;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  position: sticky;
  bottom: 0;
  z-index: 10;
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.dataset-content-wrapper {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 6px; /* 为滚动条预留空间 */
  padding-bottom: 20px; /* 为分页腾出空间 */
}

/* 美化滚动条 */
.dataset-content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.dataset-content-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.dataset-content-wrapper::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 上传组件样式 */
.upload-demo {
  width: 100%;
}

.el-upload__tip {
  line-height: 1.5;
  margin-top: 8px;
}
</style>